package com.jingwei.service.springsecurity;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jingwei.domain.Permission;
import com.jingwei.domain.RolePermission;
import com.jingwei.domain.User;
import com.jingwei.domain.UserRole;
import com.jingwei.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 经纬
 * @since 2025/1/15 14:01
 */
@RequiredArgsConstructor
public class CustomerUserDetailsServiceImpl implements UserDetailsService {
    private final UserService userService;
    private final PermissionService permissionService;
    private final UserRoleService userRoleService;
    private final RolePermissionService rolePermissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过名称查询用户信息
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username);
        User user = userService.getOne(queryWrapper);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //根据用户信息获取权限信息
        List<Permission> permissions = getPermissions(user);
        String[] strings = permissions.stream()
                .filter(Objects::nonNull)
                .map(Permission::getAuth)
                .filter(Objects::nonNull).toArray(String[]::new);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        user.setAuthorities(authorityList);
        user.setPermissions(permissions);
        return user;
    }

    /**
     * 根据用户获取权限信息
     * @param user 用户信息
     * @return 权限信息列表\菜单
     */
    private List<Permission> getPermissions(User user) {
        //通过uid获取角色
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = Wrappers.lambdaQuery(UserRole.class)
                .eq(UserRole::getUId, user.getId());
        List<UserRole> roleList = userRoleService.list(userRoleLambdaQueryWrapper);
        if (roleList.isEmpty()) {
            throw new UsernameNotFoundException("该用户无权限访问");
        }
        List<Integer> ridList = roleList.stream().map(UserRole::getRId).collect(Collectors.toList());
        //通过角色获取权限
        LambdaQueryWrapper<RolePermission> rolePermissionLambdaQueryWrapper = Wrappers.lambdaQuery(RolePermission.class)
                .in(RolePermission::getRId, ridList);
        List<RolePermission> rolePermissionList = rolePermissionService.list(rolePermissionLambdaQueryWrapper);
        if (rolePermissionList.isEmpty()) {
            throw new UsernameNotFoundException("该用户无权限访问");
        }
        List<Integer> pidList = rolePermissionList.stream().map(RolePermission::getPId).collect(Collectors.toList());
        return permissionService.list(Wrappers.lambdaQuery(Permission.class)
                .in(Permission::getId, pidList));
    }
}
